package com.faner.fast.upms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.faner.fast.upms.domain.bo.DeptTree;
import com.faner.fast.upms.model.SysDeptDO;
import com.faner.fast.upms.mapper.SysDeptMapper;
import com.faner.fast.upms.model.SysDeptRelationDO;
import com.faner.fast.upms.service.SysDeptRelationService;
import com.faner.fast.upms.service.SysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.faner.fast.upms.util.FastSecurityUtils;
import com.faner.fast.util.TreeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 部门管理 服务实现类
 * </p>
 *
 * @author faner
 * @since 2021-01-29
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDeptDO> implements SysDeptService {

    private final SysDeptRelationService sysDeptRelationService;

    /**
     * 添加信息部门
     * @param dept 部门
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveDept(SysDeptDO dept) {
        SysDeptDO sysDept = new SysDeptDO();
        BeanUtils.copyProperties(dept, sysDept);
        this.save(sysDept);
        sysDeptRelationService.saveDeptRelation(sysDept);
        return Boolean.TRUE;
    }

    /**
     * 删除部门
     * @param id 部门 ID
     * @return 成功、失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeDeptById(Long id) {
        // 级联删除部门
        List<Long> idList = sysDeptRelationService
                .list(Wrappers.<SysDeptRelationDO>query().lambda().eq(SysDeptRelationDO::getAncestor, id)).stream()
                .map(SysDeptRelationDO::getDescendant).collect(Collectors.toList());

        if (CollUtil.isNotEmpty(idList)) {
            this.removeByIds(idList);
        }

        // 删除部门级联关系
        sysDeptRelationService.removeDeptRelationById(id);
        return Boolean.TRUE;
    }

    /**
     * 更新部门
     * @param sysDept 部门信息
     * @return 成功、失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateDeptById(SysDeptDO sysDept) {
        // 更新部门状态
        this.updateById(sysDept);
        // 更新部门关系
        SysDeptRelationDO relation = new SysDeptRelationDO();
        relation.setAncestor(sysDept.getParentId());
        relation.setDescendant(sysDept.getId());
        sysDeptRelationService.updateDeptRelation(relation);
        return Boolean.TRUE;
    }

    /**
     * 查询全部部门树
     * @return 树
     */
    @Override
    public List<DeptTree> listDeptTrees() {
        return getDeptTree(this.list(Wrappers.emptyWrapper()));
    }

    /**
     * 查询用户部门树
     * @return 树
     */
    @Override
    public List<DeptTree> listCurrentUserDeptTrees() {
        Long deptId = FastSecurityUtils.getUser().getDeptId();
        List<Long> descendantIdList = sysDeptRelationService
                .list(Wrappers.<SysDeptRelationDO>query().lambda().eq(SysDeptRelationDO::getAncestor, deptId)).stream()
                .map(SysDeptRelationDO::getDescendant).collect(Collectors.toList());

        List<SysDeptDO> deptList = baseMapper.selectBatchIds(descendantIdList);
        return getDeptTree(deptList);
    }

    /**
     * 构建部门树
     * @param depts 部门
     * @return
     */
    private List<DeptTree> getDeptTree(List<SysDeptDO> depts) {
        List<DeptTree> treeList = depts.stream().filter(dept -> !dept.getId().equals(dept.getParentId()))
                .sorted(Comparator.comparingInt(SysDeptDO::getSort)).map(dept -> {
                    DeptTree node = new DeptTree();
                    node.setId(dept.getId());
                    node.setParentId(dept.getParentId());
                    node.setName(dept.getName());
                    return node;
                }).collect(Collectors.toList());
        return TreeUtil.build(treeList, 0);
    }

}
